package br.com.gsc.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import br.com.gsc.model.tableMapping.Topic;
import br.com.gsc.repository.objRepos.TopicRepository;

@Controller
@RequestMapping("/search**")
public class searchController {
	
	@Autowired
	TopicRepository tRepo;
	
	@RequestMapping(value="/search.html", method=RequestMethod.POST)
	public ModelAndView searchTopics(@RequestParam("criteria_qs") String search){
		
		ModelAndView model = new ModelAndView("search");
		List<Topic> topics = tRepo.listTopicByName(search);
		model.addObject("topics", topics);
		return model;
	}
	
	@RequestMapping(value="/searchajax.html", method=RequestMethod.GET)
	public @ResponseBody ModelAndView ajaxSearchTopics(@RequestParam("criteria_qs") String search){	
		ModelAndView model = new ModelAndView("search");
		List<searchController.TopicWrapper> topics = new ArrayList<searchController.TopicWrapper>();
		for(Topic x : tRepo.listTopicByName(search)){
			searchController.TopicWrapper topic = new searchController.TopicWrapper();
			topic.name = x.getTopicTitle();
//			URL example : /GSC/1/produto/1/topico/24.html
			topic.url = "/GSC/"+x.getProduct().getCompany().getId()+
						"/produto/"+x.getProduct().getId()+
						"/topico/"+x.getId()+".html";
			topics.add(topic);
		}
		model.addObject("topics", topics);	
		return model;
	}
	
	
	class TopicWrapper implements Serializable{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private String name;
		private String url;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		
		
	}
}


